import sys
import util
import uiconst
import uicls

def ResaveRes(save = 0):
    global os
    import os.path
    import blue
    print '----------------------------------------------------------------------------------------'

    def AddFile(files, dirname, names):
        for each in names:
            if (each[-5:] == '.blue'):
                path = os.path.join(dirname, each).replace(blue.os.respath, 'res:/').replace('\\', '/')
                files.append(path)



    files = []
    os.path.walk(blue.os.respath, AddFile, files)
    for path in files:
        print 'Saving:',
        print path
        s = blue.os.LoadObject(path)
        if save:
            s.SaveTo(path)

    print 'Done!-----------------------------------------------------------------------------------'



def _GetExports():
    ret = {}
    for each in globals().keys():
        if (each[0] != '_'):
            ret[('tools.' + each)] = globals()[each]

    return ret



def RenderIcons():
    import uix
    import draw
    import blue
    import trinity
    i = 0
    m = 200
    l = 0
    t = 0
    color = ((77 / 256.0),
     (77 / 256.0),
     (87 / 256.0))
    uix.Flush(eve.triapp.uilib.desktop)
    uicls.Fill(parent=eve.triapp.uilib.desktop, align=uiconst.TOALL, color=color)
    d = eve.triapp.uilib.desktop
    for each in cfg.invtypes:
        if not each.iconID:
            continue
        iconNo = util.IconFile(each.iconID)
        if not iconNo:
            continue
        if (t >= d.height):
            Render()
            uix.Flush(eve.triapp.uilib.desktop)
            uicls.Fill(parent=eve.triapp.uilib.desktop, align=uiconst.TOALL, color=color)
            l = 0
            t = 0
        icon = uicls.Icon(icon=iconNo, parent=d, left=l, top=t, size=64, align=uiconst.RELATIVE, idx=0)
        icon.name = repr(each.typeID)
        l += 64
        if (l >= d.width):
            l = 0
            t += 64
        i += 1

    Render()



def Render():
    import uix
    import draw
    import blue
    import trinity
    blue.pyos.synchro.Sleep(1000)
    dev = trinity.device
    sur = dev.CreateOffscreenPlainSurface(dev.adapterWidth, dev.adapterHeight, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
    dev.GetFrontBufferData(0, sur)
    wr = eve.triapp.GetWindowRect()
    cr = eve.triapp.GetClientRect()
    left = (wr.left + cr.left)
    right = (wr.left + cr.right)
    top = (wr.top + cr.top)
    bot = (wr.top + cr.bottom)
    for each in eve.triapp.uilib.desktop.children:
        try:
            int(each.name)
        except:
            continue
        print 'each',
        print each.name
        (el, et, ew, eh,) = each.GetAbsolute()
        rr = trinity.TriRect((left + el), (top + et), ((left + el) + ew), ((top + et) + eh))
        sur.SaveSurfaceToFile(('%sTemp/typeID_%s_Grey.jpg' % (blue.os.respath, each.name)), trinity.TRIIFF_JPG, rr)

    blue.pyos.synchro.Yield()



def RefreshTextures():
    textures = eve.triapp.uilib.desktop.Find('trinity.TriTexture')
    paths = {}
    for t in textures:
        if (t.pixels and ((t.pixels not in paths) and t.pixels.endswith('.dds'))):
            paths[t.pixels] = t

    for (path, t,) in paths.iteritems():
        print path
        t.Invalidate()




def TestLabel(txt = None, fontsize = 12):
    import uix
    import blue
    if (txt is None):
        txt = ('as\xe6fdglka dfl\xe6kadf\xe6lkajdf\xe6lkajs df\xe6lkafdj\xe6 asdfkjh ad<b>fkljh<u>adfkljahs dfkljahdfkljashd flkjash dfkljadfkljadfkljahfj </b></u>' * 50)
    for each in eve.triapp.uilib.desktop.children:
        if (each.name == 'text'):
            each.Close()

    s = blue.os.GetTime(1)
    t = uicls.Label(text=txt, parent=eve.triapp.uilib.desktop, width=512, autowidth=False, left=128, top=256, idx=0, fontsize=fontsize, state=uiconst.UI_NORMAL)
    e = blue.os.TimeDiffInMs(s, blue.os.GetTime(1))
    print 'LABEL:',
    print e



def CheckBlueFilesInScripts(bluefiles, dirname, names):
    import os
    import blue
    path = each = None
    print '.',
    for each in names:
        if (each[-3:] == '.py'):
            tmp = open(os.path.join(dirname, each), 'r')
            lines = tmp.readlines()
            for line in lines:
                line = line.lower()
                end = line.find('.blue')
                if (line.find('.blue') >= 0):
                    beg = line.find('res:')
                    if (beg != -1):
                        sliced = line[beg:(end + 5)].lower().replace('\\', '/')
                        if (sliced not in bluefiles):
                            bluefiles.append(sliced)


    blue.pyos.synchro.Yield()



def AddBlueFiles(bluefiles, dirname, names):
    import os
    import blue
    for each in names:
        if (each[-5:] == '.blue'):
            path = os.path.join(dirname, each).replace(blue.os.respath, 'res:/').replace('\\', '/')
            bluefiles.append(path.lower())




def CheckBlueFiles():
    import os
    import blue
    bluefilesinPy = []
    os.path.walk(blue.os.scriptpath, CheckBlueFilesInScripts, bluefilesinPy)
    bluefilesinPy.sort()
    for each in bluefilesinPy:
        print each

    print ('-' * 100)
    bluefilesinRes = []
    os.path.walk((blue.os.respath + 'UI/'), AddBlueFiles, bluefilesinRes)
    bluefilesinRes.sort()
    filterOut = ['res:/ui/icon',
     'res:/ui/shader',
     'res:/ui/station/paintshop/lib/']
    for each in bluefilesinRes[:]:
        for fo in filterOut:
            if each.startswith(fo):
                bluefilesinRes.remove(each)


    bluefilesinResNotInPy = []
    for bluepath in bluefilesinRes:
        if (bluepath not in bluefilesinPy):
            bluefilesinResNotInPy.append(bluepath)

    for each in bluefilesinResNotInPy:
        print each

    print 'Done',
    print len(bluefilesinResNotInPy)



def CheckCorpLogos():
    import os
    import blue
    import trinity
    bluefilesinRes = []
    os.path.walk((blue.os.respath + 'UI/Station/Paintshop/Lib/LayerShape/'), AddBlueFiles, bluefilesinRes)
    bluefilesinRes.sort()
    for each in bluefilesinRes:
        t = blue.os.LoadObject(each)
        if (t.textureTransformFlags != trinity.TRITTFF_COUNT2):
            print 'NOT CORRECT',
            print each
            t.textureTransformFlags = trinity.TRITTFF_COUNT2
            t.SaveTo(each)




def MapIcons(startat = 1, texturecount = 1, size = 64):
    import trinity
    texture = trinity.TriTexture()
    for i in xrange(startat, (startat + texturecount)):
        count = 0
        texture.pixels = ('res:/UI/Texture/Icons/icons%s%s.blue' % (['0', ''][(i >= 10)], i))
        texture.scaling.SetXYZ((size / 256.0), (size / 256.0), 1.0)
        for y in xrange((256 / size)):
            for x in xrange((256 / size)):
                texture.translation.x = ((size / 256.0) * x)
                texture.translation.y = ((size / 256.0) * y)
                texture.SaveTo(('res:/UI/Icon/Mapped/icon%s%s_%s%s.blue' % (['0', ''][(i >= 10)],
                 i,
                 ['0', ''][(count >= 10)],
                 count)))
                count += 1






def MapPlayerCorpLogos(startat = 1, texturecount = 1, count = 0):
    import trinity
    texture = trinity.TriTexture()
    for i in xrange(startat, (startat + texturecount)):
        texture.pixels = ('res:/UI/Texture/LogoLib%s%s.dds' % (['0', ''][(i >= 10)], i))
        print 'Texture',
        print ('res:/UI/Texture/LogoLib%s%s.dds' % (['0', ''][(i >= 10)], i))
        texture.scaling.SetXYZ((64 / 256.0), (64 / 256.0), 1.0)
        for y in xrange((256 / 64)):
            for x in xrange((256 / 64)):
                texture.translation.x = ((64 / 256.0) * x)
                texture.translation.y = ((64 / 256.0) * y)
                print ('   res:/UI/Station/Paintshop/Lib/LayerShape/%s.blue' % count),
                print texture.translation
                texture.SaveTo(('res:/UI/Station/Paintshop/Lib/LayerShape/%s.blue' % count))
                count += 1






def MapPlayerNewCorpLogos(startat = 1, texturecount = 1, count = 0, big = 0):
    import trinity
    import os
    import blue
    texture = trinity.TriTexture()
    path = 'res:/UI/Station/Paintshop/Lib/LayerShape/'
    logolibPath = 'res:/UI/Texture/corpLogoLibs/'
    if big:
        iconSize = 256
        textureSize = 512.0
        path = ('%s%s' % (path, 'large/'))
        logolibPath = ('%s%s' % (logolibPath, 'large/'))
    else:
        iconSize = 128
        textureSize = 256.0
    realPath = blue.rot.PathToFilename(path)
    if not os.path.isdir(realPath):
        try:
            os.makedirs(realPath)
        except Exception, e:
            return UserError('cannot create the folders I need')
    for i in xrange(startat, (startat + texturecount)):
        for j in xrange(1, 5):
            texture.pixels = ('%slogolib%s%s0%s.dds' % (logolibPath,
             ['0', ''][(i >= 10)],
             i,
             j))
            texture.scaling.SetXYZ((iconSize / textureSize), (iconSize / textureSize), 1.0)
            texture.textureTransformFlags = trinity.TRITTFF_COUNT2
            for y in xrange((textureSize / iconSize)):
                for x in xrange((textureSize / iconSize)):
                    texture.translation.x = ((iconSize / textureSize) * x)
                    texture.translation.y = ((iconSize / textureSize) * y)
                    trinity.Save(texture, ('%s%s.red' % (path, count)))
                    count += 1







def MapSpecial(big = 0):
    import trinity
    texture = trinity.TriTexture()
    texture.scaling.SetXYZ(0.5, 0.5, 1.0)
    texture.textureTransformFlags = trinity.TRITTFF_COUNT2
    path = 'res:/UI/Station/Paintshop/Lib/LayerShape/'
    if big:
        path = ('%s%s' % (path, 'large/'))
        texture.pixels = 'res:/UI/Texture/corpLogoLibs/large/logolib1101.dds'
    else:
        texture.pixels = 'res:/UI/Texture/corpLogoLibs/logolib1101.dds'
    components = [(0, 0.0, 0.5),
     (97, 0.0, 0.5),
     (98, 0.5, 0.0),
     (99, 0.0, 0.0)]
    for comp in components:
        (num, x, y,) = comp
        texture.translation.x = x
        texture.translation.y = y
        trinity.Save(texture, ('%s%s.red' % (path, num)))




def PrintAll(wnd, on = 1):
    for child in wnd.children:
        if hasattr(child, 'printall'):
            child.printall = on
        PrintAll(child, on)

    if hasattr(wnd, 'printall'):
        wnd.printall = on



def GenerateTextureReport(texname):
    global os
    import os.path
    import blue
    print '----------------------------------------------------------------------------------------'
    print ('Searching for files using texture containing %s in its name' % texname)
    print '----------------------------------------------------------------------------------------'

    def AddFile(files, dirname, names):
        for each in names:
            if (each[-5:] == '.blue'):
                path = os.path.join(dirname, each).replace(blue.os.respath, 'res:/').replace('\\', '/')
                try:
                    filetextures = eve.rot.GetInstance(path).Find('trinity.TriTexture')
                    for tex in filetextures:
                        if (tex.pixels.find(texname) >= 0):
                            if not files.has_key(path):
                                files[path] = []
                            if (tex.pixels not in files[path]):
                                files[path].append(tex.pixels)
                        else:
                            continue

                except blue.error, e:
                    sys.exc_clear()
                    print each,
                    print '///////////',
                    print e



    files = {}
    os.path.walk(blue.os.respath, AddFile, files)
    savetodel = []
    icons = []
    for each in files.keys():
        icon = IsInIcons(each)
        print 'Bluefile             :',
        print each
        print 'Textures             :',
        print '  /  '.join(files[each])
        print 'Icon                 :',
        print icon
        if icon:
            print 'Icon                 :',
            print icon.iconFile
            tids = UsedByTypes(icon.iconID)
            print 'Icon Used by types:',
            print tids
        print ''
        if (each[:13] == 'res:/UI/Icon/'):
            if (icon is None):
                savetodel.append(each)
            else:
                icons.append(icon)

    print '----------------------------------------------------------------------------------------'
    print 'Done',
    print len(files),
    print 'were found',
    print len(savetodel)
    if len(savetodel):
        savetodel.sort()
        blue.pyos.synchro.Yield()
        print '----------------------------------------------------------------------------------------'
        print 'These are save to delete:'
        print '----------------------------------------------------------------------------------------'
        for each in savetodel:
            print '  ',
            print each




def IsInIcons(path, *args):
    for each in cfg.icons:
        if (each.iconFile == path):
            return each




def UsedByTypes(iconID):
    types = [ each.typeID for each in cfg.invtypes if (each.iconID == iconID) ]
    return types



def UsedByDogmaAttribs(iconID):
    attrids = [ each.attributeID for each in cfg.dgmattribs if (each.iconID == iconID) ]
    return attrids



def UsedByDogmaEffects(iconID):
    effects = [ each.effectID for each in cfg.dgmeffects if (each.iconID == iconID) ]
    return effects



def PrintGIDReport():
    print 'PrintGIDReport'
    notused = []
    for each in cfg.icons:
        print '------'
        if (each.iconFile != ''):
            continue
        tids = UsedByTypes(each.iconID)
        dgma = UsedByDogmaAttribs(each.iconID)
        dgme = UsedByDogmaEffects(each.iconID)
        if not len(((tids + dgma) + dgme)):
            notused.append(each)
            continue
        print 'IconID                   : ',
        print each.iconID
        print 'Used by types            : ',
        print tids
        print 'Used by dogma attributes : ',
        print dgma
        print 'Used by dogma effects    : ',
        print dgme
        print ''

    print ('-' * 125)
    if len(notused):
        print ('-' * 125)
        print 'There are ',
        print len(notused),
        print 'iconIDs not used anywhere'
        print ('-' * 125)



def GenerateFontTest(fontSize = 8):
    import form
    c = CharacterSet()
    b = sm.GetService('window').GetWindow('virtualbrowser', decoClass=form.VirtualBrowser, create=1)
    s = '<html><body>'
    for i in xrange(0, len(c), 3):
        subseti = ('%(letter)s <b>%(letter)s</b> <i>%(letter)s</i> <b><i>%(letter)s</i></b> ' % {'letter': c[i]})
        subset = ('%(letter)s <b>%(letter)s</b>' % {'letter': c[i]})
        s += ('\n            %(letterName)s - <font size=%(fontSize)s>%(subseti)s</font><br>\n        ' % {'letter': c[i],
         'letterName': c[(i + 1)],
         'htmlLetter': c[(i + 2)],
         'subset': subset,
         'subseti': subseti,
         'fontSize': fontSize})

    s += '</html></body>'
    b.LoadHTML(s)



def GenerateAllFontTest():
    import form
    c = CharacterSet()
    b = sm.GetService('window').GetWindow('virtualbrowser', decoClass=form.VirtualBrowser, create=1)
    s = '<html><body>'
    for i in xrange(0, len(c), 3):
        subseti = ('%(letter)s <b>%(letter)s</b> <i>%(letter)s</i> <b><i>%(letter)s</i></b> ' % {'letter': c[(i + 2)]})
        subset = ('%(letter)s <b>%(letter)s</b>' % {'letter': c[i]})
        s += ('\n            %(letterName)s - %(htmlLetter)s - <br>\n            <font size=10>%(subseti)s</font>\n            <font size=14>%(subseti)s</font>\n            <font size=24>%(subseti)s</font>\n            <font size=36>%(subseti)s</font>\n            <br>\n        ' % {'letter': c[i],
         'letterName': c[(i + 1)],
         'htmlLetter': c[(i + 2)],
         'subset': subset,
         'subseti': subseti})

    s += '</html></body>'
    b.LoadHTML(s)



def TimeEula():
    import form
    import blue
    startTime = blue.os.GetTime(1)
    b = sm.GetService('window').GetWindow('virtualbrowser', decoClass=form.VirtualBrowser, create=1)
    b.LoadHTML(mls.EVE_EULA)
    now = blue.os.GetTime(1)
    print 'Eule Loaded in ',
    print blue.os.TimeDiffInMs(startTime, now)



def Alphabet():
    return ' !"#$%&\'()*+,-./0123456789:;<=>?ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff@'



def CharacterSet():
    c = [' ',
     'space',
     '&nbsp;',
     '0',
     'digit 0',
     None,
     '1',
     'digit 1',
     None,
     '2',
     'digit 2',
     None,
     '3',
     'digit 3',
     None,
     '4',
     'digit 4',
     None,
     '5',
     'digit 5',
     None,
     '6',
     'digit 6',
     None,
     '7',
     'digit 7',
     None,
     '8',
     'digit 8',
     None,
     '9',
     'digit 9',
     None,
     '%',
     'percent sign',
     None,
     '\x89',
     'permill sign',
     '&permil;',
     '#',
     'number sign',
     None,
     '\xb9',
     'superscript one',
     '&sup1;',
     '\xb2',
     'superscript two',
     '&sup2;',
     '\xb3',
     'superscript three',
     '&sup3;',
     '\xbc',
     'one-fourth',
     '&frac14;',
     '\xbd',
     'one-half',
     '&frac12;',
     '\xbe',
     'three-fourths',
     'three-fourths',
     'A',
     'A',
     None,
     '\xc0',
     'Agrave',
     '&Agrave;',
     '\xc1',
     'Aacute',
     '&Aacute;',
     '\xc2',
     'Acircumflex',
     '&Acirc;',
     '\xc3',
     'Atilde',
     '&Atilde;',
     '\xc4',
     'Aumlaut',
     '&Auml;',
     '\xc5',
     'Aring',
     '&Aring;',
     '\xc6',
     'AE',
     '&AElig;',
     'B',
     'B',
     None,
     'C',
     'C',
     None,
     '\xc7',
     'Ccedilla',
     '&Ccedil;',
     'D',
     'D',
     None,
     '\xd0',
     'Eth',
     '&ETH;',
     'E',
     'E',
     None,
     '\xc8',
     'Egrave',
     '&Egrave;',
     '\xc9',
     'Eacute',
     '&Eacute;',
     '\xca',
     'Ecircumflex',
     '&Ecirc;',
     '\xcb',
     'Eumlaut',
     '&Euml;',
     'F',
     'F',
     None,
     'G',
     'G',
     None,
     'H',
     'H',
     None,
     'I',
     'I',
     None,
     '\xcc',
     'Igrave',
     '&Igrave;',
     '\xcd',
     'Iacute',
     '&Iacute;',
     '\xce',
     'Icircumflex',
     '&Icirc;',
     '\xcf',
     'Iumlaut',
     '&Iuml;',
     'J',
     'J',
     None,
     'K',
     'K',
     None,
     'L',
     'L',
     None,
     'M',
     'M',
     None,
     'N',
     'N',
     None,
     '\xd1',
     'Ntilde',
     '&Nilde;',
     'O',
     'O',
     None,
     '\xd2',
     'Ograve',
     '&ograve;',
     '\xd3',
     'Oacute',
     '&Oacute;',
     '\xd4',
     'Ocircumflex',
     '&Ocirc;',
     '\xd5',
     'Otilde',
     '&Otilde;',
     '\xd6',
     'Oumlaut',
     '&Ouml;',
     '\xd8',
     'Oslash',
     '&Oslash;',
     '\x8c',
     'OE',
     '&OElig;',
     'P',
     'P',
     None,
     'Q',
     'Q',
     None,
     'R',
     'R',
     None,
     'S',
     'S',
     None,
     '\x8a',
     '(S me\xf0 k\xf3r\xf3nu)',
     None,
     '$',
     'dollar sign',
     None,
     'T',
     'T',
     None,
     'U',
     'U',
     None,
     '\xd9',
     'Ugrave',
     '&Ugrave;',
     '\xda',
     'Uacute',
     '&Uacute;',
     '\xdb',
     'Ucircumflex',
     '&Ucirc;',
     '\xdc',
     'Uumlaut',
     '&Uuml;',
     'V',
     'V',
     None,
     'W',
     'W',
     None,
     'X',
     'X',
     None,
     'Y',
     'Y',
     None,
     '\xdd',
     'Yacute',
     '&Yacute;',
     '\x9f',
     'Yumlaut',
     '&Yuml; ',
     '\xa5',
     'yen sign',
     '&yen;',
     'Z',
     'Z',
     None,
     '\x8e',
     '(Z me\xf0 k\xf3r\xf3nu)',
     None,
     '\xde',
     'Thorn',
     '&THORN;',
     '\x99',
     'trademark',
     '&trade;',
     'a',
     'a',
     None,
     '\xe0',
     'agrave',
     '&agrave;',
     '\xe1',
     'aacute',
     '&aacute;',
     '\xe2',
     'acircumflex',
     '&acirc;',
     '\xe3',
     'atilde',
     '&atilde;',
     '\xe4',
     'aumlaut',
     '&auml;',
     '\xe5',
     'aring',
     '&aring;',
     '\xe6',
     'ae',
     '&aelig;',
     'b',
     'b',
     None,
     'c',
     'c',
     None,
     '\xe7',
     'ccedilla',
     '&ccedil;',
     '\xa2',
     'cent sign',
     '&cent;',
     'd',
     'd',
     None,
     '\xf0',
     'eth',
     '&eth;',
     'e',
     'e',
     None,
     '\xe8',
     'egrave',
     '&egrave;',
     '\xe9',
     'eacute',
     '&eacute;',
     '\xea',
     'ecircumflex',
     '&ecirc;',
     '\xeb',
     'eumlaut',
     '&euml;',
     'f',
     'f',
     None,
     'g',
     'g',
     None,
     'h',
     'h',
     None,
     'i',
     'i',
     None,
     '\xec',
     'igrave',
     '&igrave;',
     '\xed',
     'iacute',
     '&iacute;',
     '\xee',
     'icircumflex',
     '&icirc;',
     '\xef',
     'iumlaut',
     '&iuml;',
     'j',
     'j',
     None,
     'k',
     'k',
     None,
     'l',
     'l',
     None,
     'm',
     'm',
     None,
     'n',
     'n',
     None,
     '\xf1',
     'ntilde',
     '&nilde;',
     'o',
     'o',
     None,
     '\xf2',
     'ograve',
     '&ograve;',
     '\xf3',
     'oacute',
     '&oacute;',
     '\xf4',
     'ocircumflex',
     '&ocirc;',
     '\xf5',
     'otilde',
     '&otilde;',
     '\xf6',
     'oumlaut',
     '&ouml;',
     '\xf8',
     'oslash',
     '&oslash;',
     '\x9c',
     'oe',
     '&oelig;',
     'p',
     'p',
     None,
     'q',
     'q',
     None,
     'r',
     'r',
     None,
     's',
     's',
     None,
     '\x9a',
     '(s me\xf0 k\xf3r\xf3nu)',
     None,
     't',
     't',
     None,
     'u',
     'u',
     None,
     '\xf9',
     'ugrave',
     '&ugrave;',
     '\xfa',
     'uacute',
     '&uacute;',
     '\xfb',
     'ucircumflex',
     '&ucirc;',
     '\xfc',
     'uumlaut',
     '&uuml;',
     '\xb5',
     'micro sign',
     '&micro;',
     'v',
     'v',
     None,
     'w',
     'w',
     None,
     'x',
     'x',
     None,
     'y',
     'y',
     None,
     '\xfd',
     'yacute',
     '&yacute;',
     '\xff',
     'yumlaut',
     '&yuml;',
     'z',
     'z',
     None,
     '\x9e',
     '(z me\xf0 k\xf3r\xf3nu)',
     None,
     '\xfe',
     'thorn',
     '&thorn;',
     '\xdf',
     'sharps',
     '&szlig;',
     '\x83',
     '(the eff)',
     None,
     '*',
     'asterisk',
     None,
     '\xaa',
     'feminine ordinal',
     '&ordf;',
     '\xba',
     'masculine ordinal',
     '&ordm;',
     '\x86',
     'dagger',
     '&dagger;',
     '\x87',
     'double dagger',
     '&Dagger;',
     '?',
     'question mark',
     None,
     '\xbf',
     'inverted question mark',
     '&iquest;',
     '!',
     'exclamation mark',
     None,
     '\xa1',
     'inverted exclamation ',
     '&iexcl;',
     '\xa3',
     'pound sterling',
     '&pound;',
     '\x80',
     'euro sign',
     '&euro;',
     '&',
     'ampersand',
     '&amp;',
     '@',
     'at sign',
     None,
     '\xae',
     'registered trademark',
     '&reg;',
     '\xa9',
     'copyright',
     '&copy;',
     '(',
     'left parenthesis',
     None,
     ')',
     'right parenthesis',
     None,
     '|',
     'vertical bar',
     None,
     '[',
     'left square bracket',
     None,
     ']',
     'right square bracket',
     None,
     '\xa6',
     'broken vertical bar',
     '&brvbar;',
     '{',
     'left curly brace',
     None,
     '}',
     'right curly brace',
     None,
     '+',
     'plus sign',
     None,
     '\xb1',
     'plusminus',
     '&plusmn;',
     '-',
     'minus',
     None,
     '\xf7',
     'division sign',
     '&divide;',
     '\xd7',
     'multiplication sign',
     '&times;',
     '=',
     'equals sign',
     None,
     '\xa4',
     'general currency sign',
     '&curren;',
     '~',
     'tilde',
     None,
     '\xac',
     'not sign',
     '&not;',
     '<',
     'less-than sign',
     None,
     '>',
     'greater-than sign',
     None,
     '\xab',
     'left angle quote',
     '&laquo;',
     '\xbb',
     'right angle quote',
     '&raquo;',
     '\x8b',
     'single left-pointing',
     '&lsaquo;',
     '\x9b',
     'single right-pointing',
     '&rsaquo;',
     '\\',
     'backslash',
     None,
     '/',
     'slash',
     None,
     '^',
     'caret',
     None,
     '_',
     'underscore',
     None,
     '-',
     'hyphen',
     None,
     '\x96',
     'en dash',
     '&ndash;',
     '\x97',
     'em dash',
     '&mdash;',
     '\xb4',
     'acute',
     '&acute;',
     '\xa8',
     'umlaut',
     '&uml;',
     '\x98',
     'tilde (upper)',
     '&tilde;',
     '`',
     'grave',
     '&grave;',
     '\x88',
     'circumflex',
     '&circ;',
     '\xaf',
     'macron accent',
     '&macr;',
     '\xb0',
     'degree sign',
     '&deg;',
     "'",
     'apostrophe',
     None,
     '"',
     'double quotation mark',
     '&quot;',
     '\xb8',
     'cedilla',
     '&cedil;',
     '\x85',
     'three dots',
     None,
     '.',
     'period',
     None,
     ':',
     'colon',
     None,
     ',',
     'comma',
     None,
     ';',
     'semicolon',
     None,
     '\xb7',
     'middle dot',
     '&middot;',
     '\x95',
     'bullet',
     '&bull;',
     '\x91',
     'left single quote',
     '&lsquo;',
     '\x82',
     'single low-9 quote',
     '&sbquo;',
     '\x92',
     'right single quote',
     '&rsquo;',
     '\x93',
     'left double quote',
     '&ldquo;',
     '\x84',
     'double low-9 quote',
     '&bdquo;',
     '\x94',
     'right double quote',
     '&rdquo;',
     '\x7f',
     'unused',
     None,
     '\x81',
     'unused',
     None,
     '\x8d',
     'unused',
     None,
     '\x90',
     'unused',
     None,
     '\x9d',
     'unused',
     None,
     '\xa7',
     'section sign',
     '&sect;',
     '\xb6',
     'paragraph sign',
     '&para;']
    return c



def CharacterSetMini():
    c = [' ',
     'space',
     '&nbsp;',
     '0',
     'digit 0',
     None,
     '1',
     'digit 1',
     None,
     '2',
     'digit 2',
     None,
     '3',
     'digit 3',
     None,
     '4',
     'digit 4',
     None,
     '5',
     'digit 5',
     None,
     '6',
     'digit 6',
     None,
     '7',
     'digit 7',
     None,
     '8',
     'digit 8',
     None,
     '9',
     'digit 9',
     None,
     '%',
     'percent sign',
     None,
     '\x89',
     'permill sign',
     '&permil;',
     '#',
     'number sign',
     None,
     '\xb9',
     'superscript one',
     '&sup1;',
     '\xb2',
     'superscript two',
     '&sup2;',
     '\xb3',
     'superscript three',
     '&sup3;',
     '\xbc',
     'one-fourth',
     '&frac14;',
     '\xbd',
     'one-half',
     '&frac12;',
     '\xbe',
     'three-fourths',
     'three-fourths',
     'A',
     'A',
     None,
     '\xc0',
     'Agrave',
     '&Agrave;',
     '\xc1',
     'Aacute',
     '&Aacute;',
     '\xc2',
     'Acircumflex',
     '&Acirc;',
     '\xc3',
     'Atilde',
     '&Atilde;',
     '\xc4',
     'Aumlaut',
     '&Auml;',
     '\xc5',
     'Aring',
     '&Aring;',
     '\xc6',
     'AE',
     '&AElig;',
     'B',
     'B',
     None,
     'C',
     'C',
     None,
     '\xc7',
     'Ccedilla',
     '&Ccedil;',
     'D',
     'D',
     None,
     '\xd0',
     'Eth',
     '&ETH;',
     'E',
     'E',
     None,
     '\xc8',
     'Egrave',
     '&Egrave;',
     '\xc9',
     'Eacute',
     '&Eacute;',
     '\xca',
     'Ecircumflex',
     '&Ecirc;',
     '\xcb',
     'Eumlaut',
     '&Euml;',
     'F',
     'F',
     None,
     'G',
     'G',
     None,
     'H',
     'H',
     None,
     'I',
     'I',
     None,
     '\xcc',
     'Igrave',
     '&Igrave;',
     '\xcd',
     'Iacute',
     '&Iacute;',
     '\xce',
     'Icircumflex',
     '&Icirc;',
     '\xcf',
     'Iumlaut',
     '&Iuml;',
     'J',
     'J',
     None,
     'K',
     'K',
     None,
     'L',
     'L',
     None,
     'M',
     'M',
     None,
     'N',
     'N',
     None,
     '\xd1',
     'Ntilde',
     '&Nilde;',
     'O',
     'O',
     None,
     '\xd2',
     'Ograve',
     '&ograve;',
     '\xd3',
     'Oacute',
     '&Oacute;',
     '\xd4',
     'Ocircumflex',
     '&Ocirc;',
     '\xd5',
     'Otilde',
     '&Otilde;',
     '\xd6',
     'Oumlaut',
     '&Ouml;',
     '\xd8',
     'Oslash',
     '&Oslash;',
     '\x8c',
     'OE',
     '&OElig;',
     'P',
     'P',
     None,
     'Q',
     'Q',
     None,
     'R',
     'R',
     None,
     'S',
     'S',
     None,
     '\x8a',
     '(S me\xf0 k\xf3r\xf3nu)',
     None,
     '$',
     'dollar sign',
     None,
     'T',
     'T',
     None,
     'U',
     'U',
     None,
     '\xd9',
     'Ugrave',
     '&Ugrave;',
     '\xda',
     'Uacute',
     '&Uacute;',
     '\xdb',
     'Ucircumflex',
     '&Ucirc;',
     '\xdc',
     'Uumlaut',
     '&Uuml;',
     'V',
     'V',
     None,
     'W',
     'W',
     None,
     'X',
     'X',
     None,
     'Y',
     'Y',
     None,
     '\xdd',
     'Yacute',
     '&Yacute;',
     '\x9f',
     'Yumlaut',
     '&Yuml; ',
     '\xa5',
     'yen sign',
     '&yen;',
     'Z',
     'Z',
     None,
     '\x8e',
     '(Z me\xf0 k\xf3r\xf3nu)',
     None,
     '\xde',
     'Thorn',
     '&THORN;',
     '\x99',
     'trademark',
     '&trade;',
     'a',
     'a',
     None,
     '\xe0',
     'agrave',
     '&agrave;',
     '\xe1',
     'aacute',
     '&aacute;',
     '\xe2',
     'acircumflex',
     '&acirc;',
     '\xe3',
     'atilde',
     '&atilde;',
     '\xe4',
     'aumlaut',
     '&auml;',
     '\xe5',
     'aring',
     '&aring;',
     '\xe6',
     'ae',
     '&aelig;',
     'b',
     'b',
     None,
     'c',
     'c',
     None,
     '\xe7',
     'ccedilla',
     '&ccedil;',
     '\xa2',
     'cent sign',
     '&cent;',
     'd',
     'd',
     None,
     '\xf0',
     'eth',
     '&eth;',
     'e',
     'e',
     None,
     '\xe8',
     'egrave',
     '&egrave;',
     '\xe9',
     'eacute',
     '&eacute;',
     '\xea',
     'ecircumflex',
     '&ecirc;',
     '\xeb',
     'eumlaut',
     '&euml;',
     'f',
     'f',
     None,
     'g',
     'g',
     None,
     'h',
     'h',
     None,
     'i',
     'i',
     None,
     '\xec',
     'igrave',
     '&igrave;',
     '\xed',
     'iacute',
     '&iacute;',
     '\xee',
     'icircumflex',
     '&icirc;',
     '\xef',
     'iumlaut',
     '&iuml;',
     'j',
     'j',
     None,
     'k',
     'k',
     None,
     'l',
     'l',
     None,
     'm',
     'm',
     None,
     'n',
     'n',
     None,
     '\xf1',
     'ntilde',
     '&nilde;',
     'o',
     'o',
     None,
     '\xf2',
     'ograve',
     '&ograve;',
     '\xf3',
     'oacute',
     '&oacute;',
     '\xf4',
     'ocircumflex',
     '&ocirc;',
     '\xf5',
     'otilde',
     '&otilde;',
     '\xf6',
     'oumlaut',
     '&ouml;',
     '\xf8',
     'oslash',
     '&oslash;',
     '\x9c',
     'oe',
     '&oelig;',
     'p',
     'p',
     None,
     'q',
     'q',
     None,
     'r',
     'r',
     None,
     's',
     's',
     None,
     '\x9a',
     '(s me\xf0 k\xf3r\xf3nu)',
     None,
     't',
     't',
     None,
     'u',
     'u',
     None,
     '\xf9',
     'ugrave',
     '&ugrave;',
     '\xfa',
     'uacute',
     '&uacute;',
     '\xfb',
     'ucircumflex',
     '&ucirc;',
     '\xfc',
     'uumlaut',
     '&uuml;',
     '\xb5',
     'micro sign',
     '&micro;',
     'v',
     'v',
     None,
     'w',
     'w',
     None,
     'x',
     'x',
     None,
     'y',
     'y',
     None,
     '\xfd',
     'yacute',
     '&yacute;',
     '\xff',
     'yumlaut',
     '&yuml;',
     'z',
     'z',
     None,
     '\x9e',
     '(z me\xf0 k\xf3r\xf3nu)',
     None,
     '\xfe',
     'thorn',
     '&thorn;',
     '\xdf',
     'sharps',
     '&szlig;',
     '\x83',
     '(the eff)',
     None,
     '*',
     'asterisk',
     None,
     '\xaa',
     'feminine ordinal',
     '&ordf;',
     '\xba',
     'masculine ordinal',
     '&ordm;',
     '\x86',
     'dagger',
     '&dagger;',
     '\x87',
     'double dagger',
     '&Dagger;',
     '?',
     'question mark',
     None,
     '\xbf',
     'inverted question mark',
     '&iquest;',
     '!',
     'exclamation mark',
     None,
     '\xa1',
     'inverted exclamation ',
     '&iexcl;',
     '\xa3',
     'pound sterling',
     '&pound;',
     '\x80',
     'euro sign',
     '&euro;',
     '&',
     'ampersand',
     '&amp;',
     '@',
     'at sign',
     None,
     '\xae',
     'registered trademark',
     '&reg;',
     '\xa9',
     'copyright',
     '&copy;',
     '(',
     'left parenthesis',
     None,
     ')',
     'right parenthesis',
     None,
     '|',
     'vertical bar',
     None,
     '[',
     'left square bracket',
     None,
     ']',
     'right square bracket',
     None,
     '\xa6',
     'broken vertical bar',
     '&brvbar;',
     '{',
     'left curly brace',
     None,
     '}',
     'right curly brace',
     None,
     '+',
     'plus sign',
     None,
     '\xb1',
     'plusminus',
     '&plusmn;',
     '-',
     'minus',
     None,
     '\xf7',
     'division sign',
     '&divide;',
     '\xd7',
     'multiplication sign',
     '&times;',
     '=',
     'equals sign',
     None,
     '\xa4',
     'general currency sign',
     '&curren;',
     '~',
     'tilde',
     None,
     '\xac',
     'not sign',
     '&not;',
     '<',
     'less-than sign',
     None,
     '>',
     'greater-than sign',
     None,
     '\xab',
     'left angle quote',
     '&laquo;',
     '\xbb',
     'right angle quote',
     '&raquo;',
     '\x8b',
     'single left-pointing',
     '&lsaquo;',
     '\x9b',
     'single right-pointing',
     '&rsaquo;',
     '\\',
     'backslash',
     None,
     '/',
     'slash',
     None,
     '^',
     'caret',
     None,
     '_',
     'underscore',
     None,
     '-',
     'hyphen',
     None,
     '\x96',
     'en dash',
     '&ndash;',
     '\x97',
     'em dash',
     '&mdash;',
     '\xb4',
     'acute',
     '&acute;',
     '\xa8',
     'umlaut',
     '&uml;',
     '\x98',
     'tilde (upper)',
     '&tilde;',
     '`',
     'grave',
     '&grave;',
     '\x88',
     'circumflex',
     '&circ;',
     '\xaf',
     'macron accent',
     '&macr;',
     '\xb0',
     'degree sign',
     '&deg;',
     "'",
     'apostrophe',
     None,
     '"',
     'double quotation mark',
     '&quot;',
     '\xb8',
     'cedilla',
     '&cedil;',
     '\x85',
     'three dots',
     None,
     '.',
     'period',
     None,
     ':',
     'colon',
     None,
     ',',
     'comma',
     None,
     ';',
     'semicolon',
     None,
     '\xb7',
     'middle dot',
     '&middot;',
     '\x95',
     'bullet',
     '&bull;',
     '\x91',
     'left single quote',
     '&lsquo;',
     '\x82',
     'single low-9 quote',
     '&sbquo;',
     '\x92',
     'right single quote',
     '&rsquo;',
     '\x93',
     'left double quote',
     '&ldquo;',
     '\x84',
     'double low-9 quote',
     '&bdquo;',
     '\x94',
     'right double quote',
     '&rdquo;',
     '\x7f',
     'unused',
     None,
     '\x81',
     'unused',
     None,
     '\x8d',
     'unused',
     None,
     '\x90',
     'unused',
     None,
     '\x9d',
     'unused',
     None,
     '\xa7',
     'section sign',
     '&sect;',
     '\xb6',
     'paragraph sign',
     '&para;']
    return c



def ShaderDirReport():
    global os
    import os.path
    import blue
    print '----------------------------------------------------------------------------------------'

    def AddFile(files, dirname, names):
        for each in names:
            if (each[-5:] == '.blue'):
                path = os.path.join(dirname, each).replace('C:/project/Gemini/Client/res/', 'res:/').replace('\\', '/')
                files.append(path)



    files = []
    os.path.walk((blue.os.respath + 'UI/'), AddFile, files)
    print len(files)
    valid = ['res:/UI/Shader/clip',
     'res:/UI/Shader/mod4',
     'res:/UI/Shader/dot_',
     'res:/UI/Shader/dot.',
     'res:/UI/Shader/tex_',
     'res:/UI/Shader/tex.',
     'res:/UI/Shader/wind']
    files_with_unshared_shaders = []
    illegal = {}
    for path in files:
        if ((path[:14] == 'res:/UI/Shader') or (path[:29] == 'res:/UI/Station/Paintshop/Lib')):
            continue
        s = eve.rot.GetInstance(path)
        shaders = s.Find('trinity.TriShader')
        for shader in shaders:
            shaderpath = shader.GetRotPath()
            if not shaderpath:
                if (path not in files_with_unshared_shaders):
                    files_with_unshared_shaders.append(path)
            else:
                if (shaderpath[:19] not in valid):
                    if not illegal.has_key(path):
                        illegal[path] = []
                    illegal[path].append(shaderpath)


    print len(files_with_unshared_shaders),
    print len(illegal)
    if len(illegal):
        print '----------------------------------------------------------------------------------------'
        print ' Files using illegal shaders:',
        print len(illegal)
        print '----------------------------------------------------------------------------------------'
        for path in illegal.keys():
            print '    ',
            print path
            for shaderpath in illegal[path]:
                print '        ',
                print shaderpath

            print ' '




def Scan():
    global os
    import os.path
    import blue
    import trinity
    print ('-' * 100)
    print 'FindClip'
    print ('-' * 100)

    def AddFile(files, dirname, names):
        for each in names:
            if (each[-5:] == '.blue'):
                path = os.path.join(dirname, each).replace('C:/p4client/main/client/res/', 'res:/').replace('\\', '/')
                files.append(path)



    files = []
    os.path.walk((blue.os.respath + 'UI/'), AddFile, files)
    bad = []
    for path in files:
        bluefile = eve.rot.GetInstance(path)
        shaders = bluefile.Find('trinity.TriShader')
        for shader in shaders:
            if (shader.zFunc != 8):
                if (path not in bad):
                    bad.append(path)


    for path in bad:
        print ('"%s",' % path)




def Open(path):
    obj = blue.os.LoadObject(path)
    eve.triapp.uilib.desktop.children.insert(0, obj)
    import app
    app.browser.Browse(obj)



def TestBrowser():
    import uthread
    e = mls.EVE_EULA
    b = uicore.cmd.OpenBrowser(None)
    uthread.new(b.LoadHTML, ('\n<HTML>\n\n<HEAD>\n\n\n\n<TITLE>Agent Conversation - Krakan Rost</TITLE>\n\n</HEAD>\n\n<BODY background-color=#00000000 link=#FFA800>\n\n%s\n\n</BODY>\n\n</HTML>\n    ' % e))


import random
from urllib import urlopen

class Trigram:
    length = 0

    def __init__(self, fn = None, text = None, lm = None):
        self.lut = {}
        if (lm is not None):
            self.parseLM(lm)
        if (text is not None):
            self.parseString(text)
        if (fn is not None):
            self.parseFile(fn)



    def parseLM(self, lm):
        self.lutLM = {}
        total = 0
        pair = '  '
        f = open(lm)
        for (z, line,) in enumerate(f):
            line = line.replace('\n', '')
            print 'LINE',
            print repr(line)
            (tri, i,) = line.split('\t ')
            print int(i),
            print repr(tri.replace('_', ' '))
            self.lutLM[tri.replace('_', ' ')] = int(i)
            total += (int(i) * 2)

        f.close()
        self.length = (total ** 0.5)
        self.lm = lm
        print 'Done parse LM',
        print self.length



    def similarityLM(self, check):
        total = 0
        totali = 0
        totalChecks = 0
        totalHits = 0
        for i in xrange(len(check)):
            x = check[i:(i + 1)]
            xx = check[i:(i + 2)]
            xxx = check[i:(i + 3)]
            xxxx = check[i:(i + 4)]
            xxxxx = check[i:(i + 5)]
            for each in (x,
             xx,
             xxx,
             xxxx,
             xxxxx):
                if (each in self.lutLM):
                    print 'Match:',
                    print repr(each)
                    total += self.lutLM[each]
                    totalHits += 1
                totalChecks += 1


        print ('totalmatch %d%% (%s)' % (((totalHits / float(totalChecks)) * 100), self.lm))



    def parseString(self, text):
        pair = '  '
        for letter in (text.strip() + ' '):
            d = self.lut.setdefault(pair, {})
            d[letter] = (d.get(letter, 0) + 1)
            pair = (pair[1] + letter)

        self.measure()
        print 'Done parse',
        print len(self.lut)



    def parseFile(self, fn):
        pair = '  '
        if ('://' in fn):
            print 'trying to fetch url, may take time...'
            f = urlopen(fn)
        else:
            f = open(fn)
        for (z, line,) in enumerate(f):
            if not (z % 1000):
                print ('line %s' % z)
            for letter in (line.strip() + ' '):
                d = self.lut.setdefault(pair, {})
                d[letter] = (d.get(letter, 0) + 1)
                pair = (pair[1] + letter)


        f.close()
        self.measure()
        self.fn = fn
        for k in self.lut.iterkeys():
            print 'pair:',
            print repr(k)
            for l in self.lut[k].iterkeys():
                print '  letter:',
                print repr(l),
                print 'occurance:',
                print self.lut[k][l]


        print 'Done parse',
        print len(self.lut)



    def measure(self):
        total = 0
        for y in self.lut.values():
            total += sum([ (x * x) for x in y.values() ])

        self.length = (total ** 0.5)



    def similarText(self, text):
        import tools
        t = tools.Trigram(text=text)
        print 't',
        print t
        return (self.fn, self.similarity(t))



    def similarity(self, other):
        lut1 = self.lut
        lut2 = other.lut
        total = 0
        for k in lut1.keys():
            if (k in lut2):
                print 'matchk',
                print repr(k)
                a = lut1[k]
                b = lut2[k]
                for x in a:
                    if (x in b):
                        print 'match',
                        print repr(x),
                        print a[x],
                        print b[x]
                        total += (a[x] * b[x])


        return (float(total) / (self.length * other.length))



    def __sub__(self, other):
        return (1 - self.similarity(other))



    def makeWords(self, count):
        text = []
        k = '  '
        while count:
            n = self.likely(k)
            text.append(n)
            k = (k[1] + n)
            if (n in ' \t'):
                count -= 1

        return ''.join(text)



    def likely(self, k):
        if (k not in self.lut):
            return ' '
        else:
            letters = []
            for (k, v,) in self.lut[k].items():
                letters.append((k * v))

            letters = ''.join(letters)
            return random.choice(letters)




def test():
    en = Trigram('http://gutenberg.net/dirs/etext97/lsusn11.txt')
    fr = Trigram('http://gutenberg.net/dirs/etext03/candi10.txt')
    fi = Trigram('http://gutenberg.net/dirs/1/0/4/9/10492/10492-8.txt')
    no = Trigram('http://gutenberg.net/dirs/1/2/8/4/12844/12844-8.txt')
    se = Trigram('http://gutenberg.net/dirs/1/0/1/1/10117/10117-8.txt')
    no2 = Trigram('http://gutenberg.net/dirs/1/3/0/4/13041/13041-8.txt')
    en2 = Trigram('http://gutenberg.net/dirs/etext05/cfgsh10.txt')
    fr2 = Trigram('http://gutenberg.net/dirs/1/3/7/0/13704/13704-8.txt')
    print 'calculating difference:'
    print ('en - fr is %s' % (en - fr))
    print ('fr - en is %s' % (fr - en))
    print ('en - en2 is %s' % (en - en2))
    print ('en - fr2 is %s' % (en - fr2))
    print ('fr - en2 is %s' % (fr - en2))
    print ('fr - fr2 is %s' % (fr - fr2))
    print ('fr2 - en2 is %s' % (fr2 - en2))
    print ('fi - fr  is %s' % (fi - fr))
    print ('fi - en  is %s' % (fi - en))
    print ('fi - se  is %s' % (fi - se))
    print ('no - se  is %s' % (no - se))
    print ('en - no  is %s' % (en - no))
    print ('no - no2  is %s' % (no - no2))
    print ('se - no2  is %s' % (se - no2))
    print ('en - no2  is %s' % (en - no2))
    print ('fr - no2  is %s' % (fr - no2))
    print '\nmaking up English'
    print en.makeWords(30)
    print '\nmaking up French'
    print fr.makeWords(30)


if (__name__ == '__main__'):
    test()
exports = _GetExports()

